package club.emergency.wechat.fastdfs.impl;

import club.emergency.wechat.fastdfs.FastDfsStorageService;
import lombok.extern.slf4j.Slf4j;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Create with IntelliJ IDEA
 * Project Name: wechat
 * Package Name: club.emergency.wechat.fastdfs.impl
 * Date: 2018/3/2710:07
 * User: 快乐的小菌菌
 * Description:
 */
@Component
@Scope("prototype")
@Slf4j
class FastDfsStorageServiceImpl implements FastDfsStorageService {

    private StorageClient storageClient;

    public FastDfsStorageServiceImpl() {
        try {
            ClientGlobal.init("/home/jifujun/wechat-service/fast_dfs.conf");
//            ClientGlobal.init(new ClassPathResource("fast_dfs.conf").getFile().getAbsolutePath());
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            storageClient = new StorageClient(trackerServer, null);
        } catch (IOException | MyException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String[] uploadFile(byte[] bytes, String extName) {
        String[] strings;
        try {
            strings = storageClient.upload_file(bytes, extName, null);
        } catch (IOException | MyException e) {
            e.printStackTrace();
            throw new RuntimeException("上传文件失败");
        }
        return strings;
    }

    @Override
    public Integer deleteFile(String groupName, String remoteFileName) {
        Integer code;
        try {
            code = storageClient.delete_file(groupName, remoteFileName);
        } catch (IOException | MyException e) {
            throw new RuntimeException("删除文件失败");
        }
        return code;
    }

}
